/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
})

*/
// 加载信息，带遮罩
let needLoadingRequestCount = 0;
let loadingTimer;
export function showLoading(title = '', mask = true) {
	if (needLoadingRequestCount === 0) {
		uni.showLoading({
			title,
			mask
		});

		// 最长60s自动关闭
		loadingTimer = setTimeout(() => {
			if (needLoadingRequestCount > 0) {
				uni.hideLoading();
			}
		}, 60000);
	}

	needLoadingRequestCount++;
}

// 隐藏遮罩
export function hideLoading() {
	if (needLoadingRequestCount <= 0) return;

	needLoadingRequestCount--;

	if (needLoadingRequestCount === 0) {
        loadingTimer && clearTimeout(loadingTimer);
		uni.hideLoading();
	}
}

let requestLoading = false
export default {
	config: {
		baseUrl: "https://unidemo.dcloud.net.cn/",
		header: {
			'Content-Type':'application/json;charset=UTF-8'
		},
		data: {},
		method: "GET",
		dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options, upload = false) {
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.url.indexOf('http') !== -1 ? options.url : options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		// 是否是广告接口
		let isAdRes = options.url.indexOf('exportProfessionalExcel') != -1
		let loadingTimeOut
		if (options.loading) {
			if (upload) {
				showLoading("图片加载中...")
			} else {
				loadingTimeOut = setTimeout(() => {
					if (requestLoading) return
					requestLoading = true
					showLoading("加载中...")
				}, 3000)
			}
		}
		//TODO 数据签名
		/*
		_token = {'token': getStorage(STOREKEY_LOGIN).token || 'undefined'},
		_sign = {'sign': sign(JSON.stringify(options.data))}
		options.header = Object.assign({}, options.header, _token,_sign)
		*/

		return new Promise((resolve, reject) => {
			let _config = null
			options.complete = (response) => {
				requestLoading = false;
				if (options.loading) {
					hideLoading();
					if (loadingTimeOut) clearTimeout(loadingTimeOut)
				}
				let statusCode = response.statusCode
				response.config = _config
				response.isAdRes = isAdRes
				response.errorToast = options.errorToast
				if (options.completeFn instanceof Function) {
					options.completeFn();
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response, resolve, reject)
					if (newResponse) {
						response = newResponse
					}
				}else if(statusCode === 200) { //成功
					resolve(response);
				} else {
					reject(response)
				}
			}

			options.fail = (e) => {
				console.log('当前网络不可用，请检查你的网络设置')
				reject({
					resultCode: -2,
					msg: '当前网络不可用，请检查你的网络设置'
				});
			}

			_config = Object.assign({}, upload ? {header: {}} : this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config,upload)
			}else{
				upload ? uni.uploadFile(_config) : uni.request(_config);
			}
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	upload(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.name = "file";
		options.formData = {
			"resType": 1,
		};
		options.filePath = data;
		return this.request(options, true)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}

